<template>
  <a-menu
    :mode="mode"
    :theme="themeStyle == '1' ? 'light' : 'dark'"
    :openKeys="openKeys"
    :selectedKeys="selectedKeys"
    @openChange="onOpenChange"
    @click="handleLink"
  >
    <a-sub-menu v-for="routes in menus" :key="routes.id">
      <template #icon><ProfileTwoTone /></template>
      <template #title>{{ routes.title }}</template>
      <a-menu-item v-for="menu in routes.children" :key="menu.id">
        <template #icon><StarTwoTone /></template>
        {{ menu.title }}
      </a-menu-item>
    </a-sub-menu>
  </a-menu>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { ProfileTwoTone, StarTwoTone } from '@ant-design/icons-vue'
  export default {
    name: 'MyMenu',
    components: {
      ProfileTwoTone,
      StarTwoTone,
    },
    props: {
      mode: String, //菜单类型，现在支持垂直(vertical)、水平(horizontal)、和内嵌模式(inline)三种
    },
    data() {
      return {
        selectedKeys: [], //当前选中的菜单项 key 数组
        openKeys: [], //当前展开的 SubMenu 菜单项 key 数组
      }
    },
    // 计算属性
    computed: {
      ...mapGetters({
        themeStyle: 'user/themeStyle',
        accessToken: 'user/accessToken',
        menus: 'user/menus',
      }),
    },
    // 页面渲染前
    created() {
      this.selectedKeys.push(this.$route.name)
      if (this.mode == 'inline') {
        var pKeys = this.$route.path.split('/')
        if (pKeys[pKeys.length - 1] == this.$route.name) {
          for (let index = 1; index < pKeys.length; index++) {
            this.openKeys.push(pKeys[index])
          }
        }
      }
    },
    // 方法
    methods: {
      onOpenChange(openKeys) {
        const latestOpenKey = openKeys.find(
          (key) => this.openKeys.indexOf(key) === -1
        )
        this.openKeys = latestOpenKey ? [latestOpenKey] : []
      },
      handleLink({ key, keyPath }) {
        this.selectedKeys = [key]
        this.openKeys = keyPath
        this.$router.push({ name: keyPath[1], query: { id: keyPath[1] } })
      },
    },
  }
</script>

<style lang="less">
  @header-height: 48px;
  .header-content {
    .ant-menu-horizontal {
      height: @header-height;
      line-height: @header-height;
      .ant-menu-submenu-title {
        height: @header-height;
        line-height: @header-height;
      }
    }
  }
</style>
